package com.wjb.xietong.getui;

import java.util.Calendar;
import com.igexin.sdk.PushConsts;
import com.wjb.xietong.component.AppGlobal;
import com.wjb.xietong.control.WJBControl;
import com.wjb.xietong.datamanager.LoginUserDataManager;
import com.wjb.xietong.ota.login.OTALogin;
import com.wjb.xietong.ota.task.OTATaskDetail;
import com.wjb.xietong.server.IRequestResultListener;
import com.wjb.xietong.server.login.LoginParam;
import com.wjb.xietong.util.LogD;
import com.wjb.xietong.util.PreferencesService;
import com.wjb.xietong.util.EnumDefine.Login_User_Info;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class GetuiReceiver extends BroadcastReceiver {

	private static final String TASK_ID = "taskId:";
	private static final String PROJECT_ID = ",projectId:";

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		LogD.output("个推 Action事件ID:" + bundle.getInt(PushConsts.CMD_ACTION));
		switch (bundle.getInt(PushConsts.CMD_ACTION)) {
		case PushConsts.GET_CLIENTID:
			// 获取ClientID(CID)
			String cid = bundle.getString("clientid");
			AppGlobal.getInstance().setClientId(cid);
			LogD.output("个推 ClientId:" + cid);
			login(context);
			break;
		case PushConsts.GET_MSG_DATA:
			// 获取透传（payload）数据
			byte[] payload = bundle.getByteArray("payload");

			// // smartPush第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
			// boolean result = PushManager.getInstance().sendFeedbackMessage(
			// context, bundle.getString("taskid"),
			// bundle.getString("messageid"), 90001);
			// LogD.output("个推第三方回执接口调用结果:" + (result ? "成功" : "失败"));
			if (payload != null) {
				String data = new String(payload);
				LogD.output("个推透传数据内容:" + data);
				if (null != data && !"".equals(data)) {
					try {
						long taskId = Long.valueOf(data.substring(
								data.indexOf(TASK_ID) + TASK_ID.length(),
								data.indexOf(PROJECT_ID)));
						long projectId = Long.valueOf(data.substring(
								data.indexOf(PROJECT_ID) + PROJECT_ID.length(),
								data.length()));
						login(true, context, taskId, projectId);
					} catch (Exception e) {
						LogD.output("Exception:" + e.getMessage());
					}
				}
			}
			break;
		default:
			break;
		}
	}

	private void login(final Context context) {
		login(false, context, 0, 0);
	}

	private void login(final boolean isNotify, final Context context,
			final long taskId, final long projectId) {
		final PreferencesService preferences = new PreferencesService(AppGlobal
				.getInstance().getApplicationContext());
		final String currentClientId = AppGlobal.getInstance().getClientId();
		final String clientId = preferences
				.getLoginUserInfoPreference(PreferencesService.PREFERENCE_KEY_USER_CLIENT_ID);
		final String userName = preferences
				.getLoginUserInfoPreference(PreferencesService.PREFERENCE_KEY_USER_NAME);
		final String userPwd = preferences
				.getLoginUserInfoPreference(PreferencesService.PREFERENCE_KEY_USER_PASSWORD);
		LogD.output("isNotify:" + isNotify);
		LogD.output("onReceive context is null:" + (null == context));
		LogD.output("taskId:" + taskId + " projectId:" + projectId);
		LogD.output("currentClientId:" + currentClientId);
		LogD.output("lastClientId:" + clientId);

		if (!isNotify) {// 如果不是通知
			if (null != clientId && clientId.equals(currentClientId)) {// 如果clientID不为null并且当前clientId与取到的一致，则不重新登录
				return;
			}
		}

		LogD.output("userName:" + userName + " userPwd:" + userPwd);
		if (null == userName || "".equals(userName) || null == userPwd
				|| "".equals(userPwd)) {
			return;
		}

		LoginParam param = new LoginParam();
		param.setUserName(userName);
		param.setUserPwd(userPwd);
		param.setClientId(clientId);
		WJBControl.requestLogin(Calendar.getInstance().getTimeInMillis(),
				param, new IRequestResultListener() {

					@Override
					public void requestSuccess(long requestUniqueID) {
						if (isNotify) {
							forwardDetailTaskScreen(context, projectId, taskId);
						} else {
							preferences.saveClientId(currentClientId);
						}
					}

					@Override
					public void requestFaield(long requestUniqueID,
							String errCode, String errMsg) {
						Toast.makeText(context, (null == errMsg) ? "登录失败，请重新登录"
								: errMsg, Toast.LENGTH_LONG).show();
						Intent intent = new Intent(context, OTALogin.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
						context.startActivity(intent);
					}
				});
	}

	/**
	 * 跳转至任务详情页面
	 * 
	 * @param context
	 * @param projectId
	 * @param taskId
	 */
	private void forwardDetailTaskScreen(Context context, long projectId,
			long taskId) {
		if (null == context) {
			LogD.output("Exception: context == " + context);
			return;
		}
		Intent taskDetailIntent = new Intent(context, OTATaskDetail.class);
		taskDetailIntent.putExtra("from_notice", false);
		taskDetailIntent.putExtra("projectId", projectId);
		taskDetailIntent.putExtra("companyId", (Long) LoginUserDataManager
				.getLoginUserInfo(Login_User_Info.COM_ID));
		taskDetailIntent.putExtra("taskId", taskId);
		taskDetailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
		taskDetailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
		context.startActivity(taskDetailIntent);
	}
}
